const AdminModel = require('../models/adminModel');
const productModel = require('../models/productModel');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

// 管理员登录
exports.login = async (req, res) => {
    try {
        console.log('收到登录请求');
        console.log('请求体:', req.body);

        const { username, password } = req.body;

        // 查找管理员
        console.log('查找管理员:', username);
        const admin = await AdminModel.findByUsername(username);
        console.log('查找结果:', admin);

        if (!admin) {
            console.log('未找到管理员账号');
            return res.status(401).json({
                code: 401,
                message: '用户名或密码错误'
            });
        }

        // 验证密码
        console.log('开始验证密码');
        console.log('输入的密码:', password);
        console.log('数据库中的密码哈希:', admin.password);
        const isMatch = await bcrypt.compare(password, admin.password);
        console.log('密码验证结果:', isMatch);

        if (!isMatch) {
            console.log('密码验证失败');
            return res.status(401).json({
                code: 401,
                message: '用户名或密码错误'
            });
        }

        // 更新登录时间
        await AdminModel.updateLoginTime(admin.id);

        // 生成 token
        const token = jwt.sign(
            {
                id: admin.id,
                username: admin.username,
                role: 'admin'
            },
            process.env.JWT_SECRET_KEY,
            { expiresIn: '24h' }
        );

        // 返回结果
        const response = {
            code: 200,
            message: '登录成功',
            data: {
                token,
                userInfo: {
                    id: admin.id,
                    username: admin.username,
                    nickname: admin.nickname,
                    avatar: admin.avatar,
                    role: 'admin'
                }
            }
        };

        console.log('返回响应:', response);
        res.json(response);

    } catch (error) {
        console.error('登录失败:', error);
        res.status(500).json({
            code: 500,
            message: '服务器内部错误'
        });
    }
};

// 获取所有用户
exports.getAllUsers = async (req, res) => {
    try {
        console.log('开始获取用户列表');
        const users = await AdminModel.getAllUsers();
        console.log('获取到的用户列表:', users);

        res.json({
            code: 200,
            message: '获取用户列表成功',
            data: users
        });
    } catch (error) {
        console.error('获取用户列表失败:', error);
        res.status(500).json({
            code: 500,
            message: error.message || '获取用户列表失败',
            error: process.env.NODE_ENV === 'development' ? error.stack : undefined
        });
    }

};

// 更新用户信息
exports.updateUser = async (req, res) => {
    try {
        const { userId } = req.params;
        const updateData = req.body;
        console.log(userId)
        console.log(updateData)
        const result = await AdminModel.updateUser(userId, updateData);
        res.json({ success: true, message: '用户更新成功' });
    } catch (error) {
        res.status(500).json({ message: '更新用户失败' });
    }
};

// 修改密码
exports.changePassword = async (req, res) => {
    try {
        const { oldPassword, newPassword } = req.body;
        const result = await AdminModel.changePassword(req.params.id, oldPassword, newPassword);
        res.json({ success: true, message: '密码修改成功' });
    } catch (error) {
        res.status(500).json({ message: '密码修改失败' });
    }
};

// 删除用户
exports.deleteUser = async (req, res) => {
    try {
        const result = await AdminModel.deleteUser(req.params.id);
        res.json({
            code: 200,
            message: '用户删除成功',
            success: true
        });
    } catch (error) {
        console.error('删除用户失败:', error);
        res.status(500).json({
            code: 500,
            message: error.message || '删除用户失败',
            success: false
        });
    }
};

// 获取所有商品
exports.getAllProducts = async (req, res) => {
    try {
        console.log('开始获取商品列表');
        const products = await AdminModel.getAllProducts();
        console.log('获取到的商品列表:', products);
        res.json(products);
    } catch (error) {
        res.status(500).json({ message: '获取商品列表失败' });
    }
};

// 创建商品
exports.createProduct = async (req, res) => {
    try {
        const productData = req.body;
        const result = await AdminModel.createProduct(productData);
        res.status(201).json({
            success: true,
            message: '商品创建成功',
            productId: result.insertId
        });
    } catch (error) {
        res.status(500).json({ message: '创建商品失败' });
    }
};

// 更新商品
exports.updateProduct = async (req, res) => {

    try {

        const { productId } = req.params;
        console.log('开始更新商品' + productId);
        const updateData = req.body;
        console.log('更新数据:', updateData);
        await AdminModel.updateProduct(productId, updateData);
        res.json({ success: true, message: '商品更新成功' });
    } catch (error) {
        res.status(500).json({ message: '更新商品失败' });
    }
};

// 删除商品
exports.deleteProduct = async (req, res) => {
    try {
        const { productId } = req.params;
        console.log(productId);


        // 调用模型层删除商品
        const result = await productModel.deleteProduct(productId);

        if (result.affectedRows > 0) {
            res.json({ success: true, message: '商品删除成功' });
        } else {
            res.status(404).json({ success: false, message: '商品不存在' });
        }
    } catch (error) {
        console.error('删除商品失败:', error);
        res.status(500).json({ success: false, message: '删除商品失败', error: error.message });
    }
};

// 获取所有订单
exports.getAllOrders = async (req, res) => {
    try {
        console.log('开始获取订单列表');
        const orders = await AdminModel.getAllOrders();
        console.log('获取到的订单列表:', orders);

        res.json({
            code: 200,
            message: '获取订单列表成功',
            data: orders
        });
    } catch (error) {
        console.error('获取订单列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取订单列表失败'
        });
    }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
    try {
        const { orderId } = req.params;
        const { status } = req.body;

        await AdminModel.updateOrderStatus(orderId, status);

        res.json({
            code: 200,
            message: '更新订单状态成功'
        });
    } catch (error) {
        console.error('更新订单状态失败:', error);
        res.status(500).json({
            code: 500,
            message: '更新订单状态失败'
        });
    }
};

// 删除订单
exports.deleteOrder = async (req, res) => {
    try {
        const { orderId } = req.params;
        await AdminModel.deleteOrder(orderId);

        res.json({
            code: 200,
            message: '删除订单成功'
        });
    } catch (error) {
        console.error('删除订单失败:', error);
        res.status(500).json({
            code: 500,
            message: '删除订单失败'
        });
    }
};

// 获取销售统计
exports.getSalesStatistics = async (req, res) => {
    try {
        const statistics = await AdminModel.getSalesStatistics();
        res.json(statistics);
    } catch (error) {
        res.status(500).json({ message: '获取销���统计失败' });
    }
};

// 获取用户统计
exports.getUserStatistics = async (req, res) => {
    try {
        const statistics = await AdminModel.getUserStatistics();
        res.json(statistics);
    } catch (error) {
        res.status(500).json({ message: '获取用户统计失败' });
    }
};

// 创建管理员
exports.createAdmin = async (req, res) => {
    try {
        console.log('收到创建管理员请求:', req.body);
        const { username, password, nickname } = req.body;

        // 参数验证
        if (!username || !password) {
            console.log('参数验证失败:', { username, password });
            return res.status(400).json({
                code: 400,
                message: '用户名或密码不能为空'
            });
        }

        // 检查用户名是否已存在
        const exists = await AdminModel.checkUsernameExists(username);
        if (exists) {
            console.log('用户名已存在:', username);
            return res.status(400).json({
                code: 400,
                message: '用户名已存在'
            });
        }

        // 创建管理员
        const adminId = await AdminModel.createAdmin({
            username,
            password,
            nickname,
            avatar: req.body.avatar,
            status: req.body.status
        });

        console.log('管理员创建成功:', adminId);
        res.status(200).json({
            code: 200,
            message: '管理员创建成功',
            data: { adminId }
        });

    } catch (error) {
        console.error('创建管理员失败:', error);
        res.status(500).json({
            code: 500,
            message: '创建管理员失败'
        });
    }
};

// 获取统计数据
exports.getStatistics = async (req, res) => {
    try {

        const statistics = await AdminModel.getStatistics();


        res.json({
            code: 200,
            message: '获取统计数据成功',
            data: statistics
        });
    } catch (error) {
        console.error('获取统计数据失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取统计数据失败'
        });
    }
};

// 获取仪表盘数据
exports.getDashboardData = async (req, res) => {
    try {
        // 获取总订单数
        const [orderRows] = await db.promise().query('SELECT COUNT(*) as count FROM orders');
        const orderCount = orderRows[0].count;

        // 获取今日订单数
        const [todayOrderRows] = await db.promise().query(`
            SELECT COUNT(*) as count 
            FROM orders 
            WHERE DATE(created_at) = CURDATE()
        `);
        const todayOrders = todayOrderRows[0].count;

        // 获取用户总数
        const [userRows] = await db.promise().query('SELECT COUNT(*) as count FROM users');
        const userCount = userRows[0].count;

        // 获取商品总数
        const [productRows] = await db.promise().query('SELECT COUNT(*) as count FROM products');
        const productCount = productRows[0].count;

        // 获取销售趋势数据
        const [salesTrend] = await db.promise().query(`
            SELECT 
                DATE(created_at) as date,
                COUNT(*) as order_count,
                SUM(total_price) as sales_amount
            FROM orders
            WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
            GROUP BY DATE(created_at)
            ORDER BY date DESC
        `);

        res.json({
            code: 200,
            message: '获取仪表盘数据成功',
            data: {
                orderCount,
                userCount,
                productCount,
                todayOrders,
                salesTrend
            }
        });
    } catch (error) {
        console.error('获取仪表盘数据失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取仪表盘数据失败'
        });
    }
};

// 获取订单详情
exports.getOrderDetail = async (req, res) => {
    try {
        const { orderId } = req.params;

        // 获取订单基本信息和关联数据
        const [orderDetails] = await db.promise().query(`
            SELECT 
                o.order_id,
                o.order_status,
                o.total_price as amount,
                o.created_at,
                o.shipping_address as address,
                u.username as customer,
                os.recipient_phone as phone,
                os.recipient_name,
                GROUP_CONCAT(DISTINCT p.name) as product_names,
                GROUP_CONCAT(p.price) as prices,
                GROUP_CONCAT(oi.quantity) as quantities,
                GROUP_CONCAT(p.image_url) as images
            FROM orders o
            LEFT JOIN users u ON o.user_id = u.user_id
            LEFT JOIN order_shipping os ON o.order_id = os.order_id
            LEFT JOIN order_items oi ON o.order_id = oi.order_id
            LEFT JOIN products p ON oi.product_id = p.product_id
            WHERE o.order_id = ?
            GROUP BY o.order_id
        `, [orderId]);

        if (!orderDetails) {
            return res.status(404).json({
                code: 404,
                message: '订单不存在'
            });
        }

        // 处理商品信息
        const productNames = orderDetails.product_names ? orderDetails.product_names.split(',') : [];
        const prices = orderDetails.prices ? orderDetails.prices.split(',').map(Number) : [];
        const quantities = orderDetails.quantities ? orderDetails.quantities.split(',').map(Number) : [];
        const images = orderDetails.images ? orderDetails.images.split(',') : [];

        // 构建商品列表
        const items = productNames.map((name, index) => ({
            id: index + 1,
            name,
            price: prices[index] || 0,
            quantity: quantities[index] || 1,
            image: images[index] || null
        }));

        // 构建响应数据
        const orderData = {
            orderNo: `ORD${orderDetails.order_id}`,
            status: orderDetails.order_status,
            amount: orderDetails.amount,
            createTime: new Date(orderDetails.created_at).toLocaleString(),
            customer: orderDetails.customer,
            phone: orderDetails.phone,
            address: orderDetails.address,
            recipientName: orderDetails.recipient_name,
            items
        };

        res.json({
            code: 200,
            message: '获取订单详情成功',
            data: orderData
        });
    } catch (error) {
        console.error('获取订单详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取订单详情失败'
        });
    }
};

// 获取拼团列表
exports.getGroupBuyList = async (req, res) => {
    try {
        const groupBuyList = await AdminModel.getGroupBuyList();
        res.json({
            code: 200,
            message: '获取拼团列表成功',
            data: groupBuyList
        });
    } catch (error) {
        console.error('获取拼团列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取拼团列表失败'
        });
    }
};

// ... 其他控制器方法 